<template>
    <div class="main commodity-tag-list">
        <div class="filter-container">
            <el-input @keyup.enter.native="search" class="filter-item" placeholder="按名称搜索" v-model="params.name"></el-input>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            <el-button v-if="rightsButtons['add']" type="success" icon="el-icon-plus" class="filter-item" @click="showAdd">新建</el-button>
        </div>
        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" label="名称" prop="name"></el-table-column>
            <el-table-column align="center" label="图片">
                <template slot-scope="scope">
                    <img :src="scope.row.tagImage" alt="" height="30"/>
                </template>
            </el-table-column>
            <el-table-column align="center" label="是否可用">
                <template slot-scope="scope">
                    <span>{{scope.row.tagStatus == 1 ? '可用' : '不可用'}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" v-if="rightsButtons['goods'] || rightsButtons['edit'] || rightsButtons['delete']">
                <template slot-scope="scope">
                    <el-button v-if="rightsButtons['goods']" type="success" size="mini" @click="$router.push({name: 'commodityTagGoods', params: {id: scope.row.id, name: scope.row.name}})">查看商品</el-button>
                    <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                    <el-button v-if="rightsButtons['delete']" type="danger" size="mini" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container" v-if="total > 0">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="page" :page-size="pageSize" :total="total" layout="total, prev, pager, next, jumper"></el-pagination>
        </div>
        <el-dialog :title="editItem.id ? '编辑标签' : '新建标签'" :visible.sync="showEditPop">
            <el-form :model="editItem" :rules="editRule" size="medium" ref="editItem" label-width="120px">
                <el-form-item label="名称:" prop="name">
                    <el-input v-model="editItem.name"></el-input>
                </el-form-item>
                <el-form-item label="图片:" prop="tagImage">
                    <el-upload
                            class="avatar-uploader"
                            accept="image/*"
                            :action="upladUrl"
                            name="file"
                            :show-file-list="false"
                            :on-success="uploadSuccess"
                            :before-upload="beforeUpload">
                        <img v-if="editItem.tagImage" :src="editItem.tagImage" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="是否可用:">
                    <el-switch
                            v-model="editItem.tagStatus"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            :active-value="1"
                            :inactive-value="0">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" :disabled="btnDisabled">保存</el-button>
                <el-button @click="showEditPop = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
  export default {
    name: 'commodityTag',
    data() {
      const validTagName = (rule, value, callback) => {
        if(!value){
          return callback(new Error('不能为空'));
        }
        if (this.editItem.id && this.editName === value) {
          return callback();
        }
        if(/[^\a-zA-Z0-9\u4e00-\u9FA5\-.]/.test(value)){
          return callback(new Error('不能含有特殊字符'));
        }
        if(value.length > 100){
          return callback(new Error('不能超过100字符'));
        }
        this.btnDisabled = true;
        this.request({
          url: '/bsnl-product/tag/name',
          method: 'get',
          params: {
            name: value
          }
        }).then(({data, status, message}) => {
          this.btnDisabled = false;
          if (data && data.id) {
            return callback(new Error('标签名已存在'));
          }
          callback();
        }).catch(err => {
          this.btnDisabled = false;
          callback(new Error(err));
        });
      };
      return {
        list: [],
        params: {
          name: ''
        },
        query: {},
        page: 1,
        pageSize: 1000,
        total: 0,
        editItem: {},
        editName: '',
        editRule: {
          name: [
            {required: true, message: '不能为空', trigger: 'change'},
            {max: 100, message: '不能超过100字符', trigger: 'change'},
            {pattern: /[\a-zA-Z0-9\u4e00-\u9FA5\-.]+$/, message: '不能含有特殊字符', trigger: 'change'},
            {validator: validTagName, trigger: 'blur'}
          ],
          tagImage: [
            {required: true, message: '请上传图片', trigger: 'change'}
          ]
        },
        showEditPop: false,
        listLoading: false,
        btnDisabled: false,
      }
    },
    created() {
      this.getList();
    },
    methods: {
      // 获取列表
      getList() {
        this.listLoading = true;
        this.request({
          url: '/bsnl-product/tag/query',
          method: 'post',
          data: {
            pageIndex: this.page,
            pageSize: this.pageSize,
            ...this.query
          }
        }).then(({data, totalCount}) => {
          this.list = data;
          this.total = totalCount;
          this.listLoading = false;
        }).catch(err => {
          console.log(err);
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
      },
      // 删除
      del(item) {
        this.$confirm(`确定要删除 ${item.name} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.request({
            url: '/bsnl-product/tag/delete',
            method: 'post',
            data: {
              id: item.id,
              deleteFlag: 0
            },
            headers: {
              authorKey: `${this.$route.name}Delete`
            }
          }).then(() => {
            if(this.page > 1 && this.list.length === 1){
              this.page--;
            }
            this.getList();
            this.$message.success('删除成功');
          }).catch(err => {
            console.log(err);
            this.list = [];
            this.total = 0;
            this.listLoading = false;
          });
        }).catch(err => {
          console.log(err);
        });
      },
      // 显示新建
      showAdd() {
        this.editItem = {
          name: '',
          tagImage: '',
          tagStatus: 0
        };
        this.showEditPop = true;
        this.btnDisabled = false;
      },
      // 显示编辑
      showEdit(item) {
        this.editItem = {...item};
        this.editName = item.name;
        this.showEditPop = true;
        this.btnDisabled = false;
      },
      // 保存
      save() {
        this.$refs.editItem.validate(valid => {
          console.log(JSON.stringify(this.editItem));
          if (!valid) {
            return false;
          }
          let url = this.editItem.id ? '/bsnl-product/tag/update' : '/bsnl-product/tag/create';
          this.btnDisabled = true;
          this.request({
            url,
            method: 'post',
            data: this.editItem,
            headers: {
              authorKey: this.editItem.id ? `${this.$route.name}Edit`:`${this.$route.name}Add`
            }
          }).then(() => {
            this.btnDisabled = false;
            this.editItem = {};
            this.showEditPop = false;
            this.$message.success('保存成功');
            this.getList();
          }).catch(err => {
            this.btnDisabled = false;
          });
        });
      },
      // 搜索
      search() {
        this.page = 1;
        this.query = {
          ...this.params
        };
        this.getList();
      },
      // 切换分页
      handleCurrentChange(page) {
        this.page = page;
        this.getList();
      },
      uploadSuccess(res, file) {
        this.editItem.tagImage = this.replaceImgUrl(res.filePath);
      },
    }
  }
</script>
